import datetime
import logging

from src.core.models.dto import UserDTO
from src.core.models.enums.user import LangCode
from src.database.models import User
from src.database.uow import SQLAlchemyUoW

logger = logging.getLogger(__name__)


class UserService:
    def __init__(self, uow: SQLAlchemyUoW):
        self._uow = uow

    async def get_user_by_id(self, user_id: int) -> UserDTO:
        """Получаем пользователя по id"""

        return await self._uow.user_reader.get_user_by_id(user_id)

    async def get_user_by_telegram_id(self, user_tg_id: int) -> UserDTO:
        """Получаем пользователя по telegram id"""

        return await self._uow.user_reader.get_user_by_tg_id(user_tg_id)

    async def get_all_users(self) -> list[UserDTO]:
        """Получаем всех пользователей"""

        return await self._uow.user_reader.get_users()

    async def change_user_lang(self, user_tg_id: int, lang_code: LangCode) -> None:
        """Изменяем язык пользователя"""

        user: User = await self._uow.user_repo.acquire_user_by_tg_id(user_tg_id)
        user.lang_code = lang_code

        await self._uow.user_repo.update_user(user)

        await self._uow.commit()

    async def create_user(self, telegram_id: int, username: str) -> None:
        """Создаем пользователя"""

        user = User(telegram_id=telegram_id, username=username)
        try:
            await self._uow.user_repo.create_user(user)
        except Exception as err:
            await self._uow.rollback()
            raise err

        await self._uow.commit()
